﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using System.Reflection;
using OznerOA.Common;
using OznerOA.Model;
using DevExpress.XtraTab;
using OznerOA.BLL;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraBars;

namespace OznerOA.UI
{
    public delegate void ControlSetPropertyHandle(Control con, string method, object value);
    public delegate object ControlExecuteMethodHandle(Control con, string method, params object[] Params);
    public partial class FrmBase : DevExpress.XtraEditors.XtraForm
    {
        protected LogBLL logBLL = null;
        public FrmBase()
        {
            logBLL = new LogBLL(this.GetType().Name, this.Text);
            InitializeComponent();
        }
        #region 设置dockPanel状态
        protected void SetDockPanelDock(DockPanel panel, BarCheckItem item, string dock, string tip)
        {
            if (dock == "DOCK")
            {
                panel.Visibility = DockVisibility.Visible;
                item.Checked = true;
                logBLL.Debug(tip + "状态:{0}", "停靠");
            }
            else if (dock == "UNDOCK")
            {
                panel.Visibility = DockVisibility.AutoHide;
                item.Checked = true;
                logBLL.Debug(tip + "状态:{0}", "自动隐藏");
            }
            else
            {
                panel.Visibility = DockVisibility.Hidden;
                item.Checked = false;
                logBLL.Debug(tip + "状态:{0}", "隐藏");
            }
        }
        #endregion




        #region TabControl添加TabPage，form

        protected void TabControlAddPageForm(XtraTabControl tab, string Caption, FrmBase frm)
        {
            //标识存在的Page
            XtraTabPage containsPage = null;
            foreach (XtraTabPage tp in tab.TabPages)
            {
                if (Caption.Equals(tp.Text))
                {
                    containsPage = tp;
                    break;
                }
            }
            if (containsPage != null)
            {
                //已经存在此tab
                tab.SelectedTabPage = containsPage;
            }
            else
            {
                //不存在则创建
                XtraTabPage page = new XtraTabPage();
                page.Text = Caption;
                tab.TabPages.Add(page);
                frm.FormBorderStyle = FormBorderStyle.None;
                frm.TopLevel = false;
                page.Controls.Add(frm);
                frm.WindowState = FormWindowState.Maximized;
                tab.SelectedTabPage = page;
                frm.Show();
            }
        }
        #endregion


        #region 解析http地址
        /// <summary>
        /// 解析例如"/abc/ddd?a=1&b=2"的地址
        /// </summary>
        protected HttpAddress ParseAddress(string address)
        {
            HttpAddress ha = new HttpAddress();
            ha.Address = address;
            //首先判断是否http/https开头
            if (address.StartsWith("http://"))
            {
                ha.Protocal = "HTTP";
                address = address.Replace("http://", "");
            }
            if (address.StartsWith("https://"))
            {
                ha.Protocal = "HTTPs";
                address = address.Replace("https://", "");
            }
            //去掉协议之后，判断是否以/开头，并去掉/
            if (address.StartsWith("/"))
            {
                address = address.Substring(1, address.Length - 1);
            }
            //处理参数
            if (address.Contains("?"))
            {
                string[] t = address.Split('?');
                address = t[0];
                string[] ps = t[1].Split('&');
                foreach (string p in ps)
                {
                    string[] kv = p.Split('=');
                    ha.Params.Add(kv[0], kv[1]);
                }
            }
            //处理models
            if (address.Contains("/"))
            {
                string[] models = address.Split('/');
                foreach (string model in models)
                {
                    ha.Models.Add(model);
                }
                ha.Page = models[models.Length - 1];
                ha.Models.RemoveAt(ha.Models.Count - 1);
            }
            else
            {
                ha.Page = address;
            }
            return ha;
        }
        #endregion

        #region 调用BLL层方法
        protected BaseResult<T> ExecuteBLL<T>(object bll, string method, params object[] Params)
        {
            MethodInfo mi = bll.GetType().GetMethod(method);
            if (mi != null)
            {
                try
                {
                    BaseResult<T> bsv = mi.Invoke(bll, Params) as BaseResult<T>;
                    if (bsv.Code == Code.LOGOUT)
                    {
                        CloseWaiting();
                        ShowLoginForm(false, bsv.Message);

                    }
                    else if (bsv.Code == Code.NULL)
                    {
                        CloseWaiting();
                        BoxHelper.Error(bsv.Message);
                    }
                    return bsv;
                }
                catch(Exception e)
                {
                    CloseWaiting();
                    logBLL.Error(string.Format("[{0}]调用方法[{1}]失败!", bll.GetType().Name, method));
                    return new BaseResult<T>
                    {
                        Code = Code.NULL
                    };
                }
            }
            else
            {
                CloseWaiting();
                logBLL.Error(string.Format("[{0}]不存在方法：{1}", bll.GetType().Name, method));
                return new BaseResult<T>
                {
                    Code = Code.NULL
                };
            }
        }
        #endregion
        #region 显示登录窗体
        protected virtual void ShowLoginForm(bool IsEnableAutoLogin, string tip)
        {
        }
        #endregion

        #region 代理执行控件
        /// <summary>
        /// 代理执行控件
        /// </summary>
        /// <param name="con"></param>
        /// <param name="Params"></param>
        public object ControlDelegateExecuteMethod(Control con, string method, params object[] Params)
        {
            if (con.InvokeRequired)
            {
                ControlExecuteMethodHandle handle = new ControlExecuteMethodHandle(ControlDelegateExecuteMethod);
                return con.Invoke(handle, con, method, Params);
            }
            else
            {
                //获取方法
                MethodInfo mi = con.GetType().GetMethod(method);
                if (mi == null)
                {
                    throw new Exception(string.Format("方法[{0}]不存在", method));
                }
                return mi.Invoke(con, Params);
            }
        }
        #endregion

        #region 代理设置属性值
        /// <summary>
        /// 代理设置属性值
        /// </summary>
        /// <param name="con"></param>
        /// <param name="property"></param>
        /// <param name="value"></param>
        public void ControlDelegateSetProperty(Control con, string property, object value)
        {
            if (!con.IsDisposed)
            {
                if (con.InvokeRequired)
                {
                    ControlSetPropertyHandle handle = new ControlSetPropertyHandle(ControlDelegateSetProperty);
                    con.Invoke(handle, con, property, value);
                }
                else
                {
                    //获取属性
                    PropertyInfo pi = con.GetType().GetProperty(property);
                    if (pi == null)
                    {
                        throw new Exception(string.Format("方法[{0}]不存在", property));
                    }
                    pi.SetValue(con, value, null);
                }
            }
        }
        #endregion

        #region SplashScreen相关

        protected void ShowWaiting(string caption)
        {
            ShowWaiting(caption, "");
        }
        protected void ShowWaiting(string caption, string description)
        {
            try
            {
                SplashScreenManager.ShowForm(this, typeof(FrmWaiting), true, true);
            }
            catch (InvalidOperationException)
            {
            }
            SplashScreenManager.Default.SetWaitFormCaption(caption);
            SplashScreenManager.Default.SetWaitFormDescription(description);
        }

        protected void UpdateCaption(string caption)
        {
            SplashScreenManager.Default.SetWaitFormCaption(caption);
        }

        protected void UpdateDescription(string description)
        {
            SplashScreenManager.Default.SetWaitFormDescription(description);
        }
        protected void UpdateCaptionDescription(string caption, string description)
        {
            SplashScreenManager.Default.SetWaitFormCaption(caption);
            SplashScreenManager.Default.SetWaitFormDescription(description);
        }

        protected void CloseWaiting()
        {
            try
            {
                SplashScreenManager.CloseForm(true);
            }
            catch (Exception) { }
        }

        #endregion
    }
}